import {
  addMonitorsDataItem,
  deleteMonitorsDataItem,
  getMonitorsDataItemList,
  importExcelMonitorsDataItem,
  judgeDataHasMonitors,
  postCompanyInfoFastSearchPageList
} from '@/api/monitors'
import { HsAdminInput, HsAdminSpin, HsAdminTable, useESPage } from '@hs-admin/base-components'
import { message } from '@hs-admin/utils'
import { useDebounceFn } from 'ahooks'
import { AutoComplete, Button, Flex, Modal, Upload } from 'antd'
import { SetStateAction, useEffect, useState } from 'react'
import './style.less'
import { useTableCheck } from '@/hooks/useMonitors'
import { UploadOutlined } from '@ant-design/icons'
import { CopyToClipboard } from 'react-copy-to-clipboard'

export default (selectedTrackItem: { id: any }) => {
  const [open, setOpen] = useState(false)
  const [options, setoptions] = useState([])
  const [selectedName, setselectedName] = useState('')
  const [data, setData] = useState<any[]>([])
  const [totalNumber, settotalNumber] = useState(0)
  const { ESPage, pagination, resetPage, setPagination } = useESPage({ total: totalNumber })
  const columns = [
    { title: '公司名称', dataIndex: 'data_name' },
    { title: '加入时间', dataIndex: 'created_at', type: 'datetime' },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_text: any, record: { data_id: any; list_id: string }) => (
        <Button
          type="link"
          onClick={() => {
            deleteMonitorsDataItem({ data_id: record.data_id, list_id: record.list_id }).then(() => {
              message.success('移除成功')
              setPagination({ ...pagination })
            })
          }}>
          移除
        </Button>
      )
    }
  ]
  const [keyword, setkeyword] = useState('')
  const { selectedRowKeys, selectedData, rowSelection } = useTableCheck()
  const { UploadExcel, doOpenExcel } = useUploadExcel(selectedTrackItem, () => {
    resetPage()
  })

  const onSelect = (value: string, option: { label: any }) => {
    setselectedName(value)
    addMonitorsDataItem({ data_id: value, data_name: option.label, list_id: selectedTrackItem.id }).then(() => {
      message.success('添加成功')
      setoptions([])
      setselectedName('')
      resetPage()
    })
  }
  const { run } = useDebounceFn(
    (keyword) => {
      postCompanyInfoFastSearchPageList({
        pageNum: 1,
        pageSize: 50,
        keyword: keyword,
        reportYear: '2023'
      }).then((res) => {
        let { list } = res.data
        const data_ids = list.map((item: { companyCode: any }) => item.companyCode)
        judgeDataHasMonitors({ data_ids }).then((res2) => {
          list = list.filter((item: { companyCode: string | number }) => !res2[item.companyCode])
          setoptions(
            res.data.list.map((item: { companyName: any; companyCode: any }) => ({
              label: item.companyName,
              value: item.companyCode
            }))
          )
        })
      })
    },
    {
      wait: 500
    }
  )

  useEffect(() => {
    settotalNumber(0)
    setData([])
    getMonitorsDataItemList({
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword,
      list_id: selectedTrackItem.id
    }).then((res) => {
      settotalNumber(res.total)
      setData(res.items)
    })
  }, [pagination])

  return {
    CompanyManageModal: (
      <>
        <Modal
          title="企业管理"
          open={open}
          width="60vw"
          footer={null}
          onCancel={() => {
            setOpen(false)
          }}>
          <h1 className="module-title mb-2">添加企业（1000内）</h1>
          <Flex align="center" gap="middle">
            <AutoComplete
              value={selectedName}
              options={options}
              onSelect={onSelect}
              onSearch={run}
              placeholder="请输入企业名称添加"
              className="w-full"
              onChange={(value) => setselectedName(value)}
              allowClear
            />
            <Button
              type="primary"
              shape="round"
              onClick={() => {
                doOpenExcel()
              }}>
              导入EXCEL（企业名称；{'<'} 1000家）
            </Button>
          </Flex>
          <Flex align="center" gap="'middle" justify="space-between" className="mt-8 mb-2">
            <Flex align="center" gap="'middle">
              <span className="flex-none">搜索已添加企业：</span>
              <HsAdminInput
                Search
                placeholder="请输入公司名称"
                onSearch={(value: SetStateAction<string>) => {
                  setkeyword(value)
                  resetPage()
                }}
                onPressEnter={(e: { target: { value: SetStateAction<string> } }) => {
                  setkeyword(e.target.value)
                  resetPage()
                }}
              />
            </Flex>
            <Flex align="center" gap="'middle">
              <Button
                type="link"
                onClick={async () => {
                  if (!selectedData.length) {
                    message.warning('请选择公司')
                    return
                  }
                  const pList: any[] = []
                  selectedData.forEach(async (item) => {
                    pList.push(deleteMonitorsDataItem({ data_id: item.data_id, list_id: item.list_id }))
                  })
                  Promise.all(pList).then(() => {
                    message.success('移除成功')
                    setPagination({ ...pagination })
                  })
                }}>
                移除选中
              </Button>
              {ESPage}
            </Flex>
          </Flex>
          <HsAdminTable
            columns={columns}
            dataSource={data}
            size="small"
            id="monitors-company-manage-list"
            rowKey={(record: any) => {
              const result = record.data_id
              return result
            }}
            rowSelection={{ selectedRowKeys, ...rowSelection }}
          />
        </Modal>
        {UploadExcel}
      </>
    ),
    doOpenCompanyManage: () => {
      resetPage()
      setOpen(true)
    }
  }
}

function useUploadExcel(selectedTrackItem: { id: any }, success: { (): void; (): void }) {
  const action: any = `${import.meta.env.VITE_DATA_QUERY_URL}/api/data-query/v1/monitors/items:upload`
  const [open, setOpen] = useState(false)
  const [upData, setUpData] = useState<any>(new FormData())
  const [companyList, setcompanyList] = useState([])
  const { UploadMsg, showUploadMsg } = useShowUploadMsg(companyList)
  const [loading, setloading] = useState(false)

  return {
    UploadExcel: (
      <>
        {loading && <HsAdminSpin />}
        <Modal
          title="导入EXCEL"
          open={open}
          width="20vw"
          onCancel={() => {
            setUpData(new FormData())
            setOpen(false)
          }}
          onOk={() => {
            if (!upData.get('file')) {
              message.warning('请上传文件')
              return
            }
            setloading(true)
            importExcelMonitorsDataItem(upData)
              .then((res) => {
                if (res.unidentification?.length) {
                  setcompanyList(res.unidentification)
                  showUploadMsg()
                } else {
                  message.success('导入成功')
                }
                setUpData(new FormData())
                setOpen(false)
                success()
              })
              .finally(() => {
                setloading(false)
              })
          }}>
          <Upload
            action={action}
            accept=".xlsx,.xls"
            maxCount={1}
            fileList={upData.get('file') ? [upData.get('file')] : undefined}
            onRemove={() => {
              setUpData((prevState: { get: (arg0: string) => any }) => {
                const newFormData = new FormData()
                const search_filed = prevState.get('search_filed')
                if (search_filed) newFormData.set('search_filed', search_filed)
                newFormData.set('list_id', selectedTrackItem.id)
                return newFormData
              })
            }}
            beforeUpload={(file) => {
              setUpData((prevState: { get: (arg0: string) => any }) => {
                const newFormData = new FormData()
                const search_filed = prevState.get('search_filed')
                newFormData.set('file', file)
                if (search_filed) newFormData.set('search_filed', search_filed)
                newFormData.set('list_id', selectedTrackItem.id)
                return newFormData
              })
              return false
            }}>
            <Button icon={<UploadOutlined />}>选择要上传的Excel文件</Button>
          </Upload>
        </Modal>
        {UploadMsg}
      </>
    ),
    doOpenExcel: () => {
      setUpData(new FormData())
      setOpen(true)
    }
  }
}

function useShowUploadMsg(companyList: any[]) {
  const [open, setOpen] = useState(false)

  return {
    UploadMsg: (
      <Modal
        title="导入结果"
        open={open}
        width="20vw"
        footer={null}
        onCancel={() => {
          setOpen(false)
        }}>
        <Flex align="center" gap={'middle'}>
          <p>以下企业未在库中被识别到，其他企业已经导入</p>
        </Flex>
        <CopyToClipboard text={companyList.join('，')}>
          <Button type="link">复制全部</Button>
        </CopyToClipboard>
        {companyList.map((item, index) => (
          <p key={index}>{item}</p>
        ))}
      </Modal>
    ),
    showUploadMsg: () => {
      setOpen(true)
    }
  }
}
